package learn;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.io.input.BOMInputStream;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.*;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class demo_RestTemplate {
    static public String get_csv(String html){
        Pattern p = Pattern.compile("textarea id.*\n.*</textarea");
        Matcher m = p.matcher(html);
        String textarea="";
        String csv_content = "";
        if (m.find()){
            textarea = m.group(0);
        }
        p=Pattern.compile("\n.*<");
        m=p.matcher(textarea);
        if(m.find()){
            csv_content = m.group();
            csv_content=csv_content.substring(1,csv_content.length()-9);
            return csv_content;
        }
        return null;
    }
    static void save_csv(String csv_content) throws IOException {
        FileWriter out=new FileWriter("result.csv");
        out.write(csv_content);
        out.close();
    }

    public static void main(String[] args) throws IOException {
        RestTemplate template = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
        template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("utf-8")));
        String url="https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
        String csv_content = template.getForObject(url,String.class);
        if(csv_content!=null){
            save_csv(csv_content);
        }
        Reader in = new InputStreamReader(new BOMInputStream(new FileInputStream("result.csv")));
        Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(in);
        for (CSVRecord record : records) {
            if(record.size()<8) continue;
            System.out.println(record.get(0));
            System.out.println(record.get(1));
        }

    }
}
